from rest_framework.response import Response
from rest_framework import status
# Create your views here.
from rest_framework import viewsets
from order.serializers import OrderSerialzier
from order.models import Order
from order.permissions import IsOnerOrAdminReadOnly
from rest_framework import mixins
from users.models import Position
from django.db.models import Q
from transactions.models import Transaction  # 这个是撮合成功的订单表
from django.db import transaction  # 这个是django实现的事务机制

from chat import TradeInfoRedis


class OrderViewSet(mixins.CreateModelMixin,
                   mixins.ListModelMixin,
                   mixins.RetrieveModelMixin,
                   viewsets.GenericViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerialzier
    permission_classes = [IsOnerOrAdminReadOnly]

    """
    def get_queryset(self):

        管理员返回所有的 非管理员返回自己的
        走到这里 已经进行过权限的认证了 确定返回的数据

        if self.request.user.is_superuser:
            return Order.objects.all()
        return Order.objects.filter(user=self.request.user)
    """

    def save_buy_order(self, request, serializer):
        """
        买入订单需要判断持有的金币情况
        """
        cnyfree = self.request.user.cny_free
        total_cny = serializer.validated_data.get('undealed') * serializer.validated_data.get('price')
        if total_cny > cnyfree:
            return Response("当前余额不足 不能发起该订单", status=status.HTTP_400_BAD_REQUEST)
        self.request.user.cny_free -= total_cny
        self.request.user.save()
        buy_order_num = int(self.request.data.get('undealed'))
        dealed_num = 0
        # 这里先保存一下 因为要获取到id写入其他的表
        buy_order_instance = serializer.save(user=self.request.user, undealed=buy_order_num, dealed=dealed_num)
        return buy_order_instance

    def sava_sell_order(self, request, serializer):
        """
        卖出订单需要判断持有情况
        """
        result = Position.objects.filter(Q(user=self.request.user) & Q(stock_id=self.request.data.get('stock')))
        if result.count() == 0:
            return Response("不持有该股票", status=status.HTTP_400_BAD_REQUEST)
        else:
            potition_instance = result.first()
            if potition_instance.num_free >= int(self.request.data.get('undealed')):
                potition_instance.num_free -= int(self.request.data.get('undealed'))
                potition_instance.save()
                sell_order_instance = serializer.save(user=self.request.user)
                return sell_order_instance
            else:
                return Response("要交易的数量超出了持有数量", status=status.HTTP_400_BAD_REQUEST)

    def exchange_buy_order(self, request, buy_order_instance, serializer):
        sell_orderlist = Order.objects.filter(
            Q(stock_id=int(self.request.data.get('stock'))) &
            Q(type=True) &
            Q(undealed__gt=0) &
            Q(price__lte=float(self.request.data.get('price'))) &
            ~Q(user_id=self.request.user.id)
        )
        print(sell_orderlist)
        buy_order_num = buy_order_instance.undealed
        dealed_num = buy_order_instance.dealed
        for order in sell_orderlist:
            if buy_order_num - order.undealed > 0:
                volume = order.undealed
                buy_order_num -= order.undealed
                order.dealed += order.undealed
                order.undealed = 0
                dealed_num += order.dealed
                order.save()
                serializer.save(id=buy_order_instance.id, undealed=buy_order_num, dealed=dealed_num)
                Transaction.objects.create(buy_order_id=buy_order_instance.id, sell_order_id=order.id,
                                           price=self.request.data.get('price'), dealed=volume,
                                           stock=int(self.request.data.get('stock')))
                print(
                    "购买订单还未完成 生成的购买订单id为{2} 撮合的出售订单id为{0} 成交数量为{1}".format(order.id, volume, buy_order_instance.id))
            else:
                volume = buy_order_num
                order.undealed -= buy_order_num
                order.dealed += buy_order_num
                dealed_num += volume
                buy_order_num = 0
                order.save()
                serializer.save(id=buy_order_instance.id, undealed=buy_order_num, dealed=dealed_num)
                Transaction.objects.create(buy_order_id=buy_order_instance.id, sell_order_id=order.id,
                                           price=self.request.data.get('price'), dealed=volume,
                                           stock=int(self.request.data.get('stock')))
                print("购买订单已完成 生成的购买订单id为{2} 撮合的订单id为{0} 成交数量为{1}".format(order.id, volume, buy_order_instance.id))
                break

    def exchange_sell_order(self, request, sell_order_instance, serializer):
        buy_orderlist = Order.objects.filter(
            Q(stock_id=int(self.request.data.get('stock'))) &
            Q(type=False) &
            Q(undealed__gt=0) &
            Q(price__gte=float(self.request.data.get('price'))) &
            ~Q(user_id=self.request.user.id)
        )
        sell_order_num = sell_order_instance.undealed
        dealed_num = sell_order_instance.dealed
        for order in buy_orderlist:
            if sell_order_num - order.undealed > 0:
                volume = order.undealed
                sell_order_num -= order.undealed
                order.dealed += order.undealed
                order.undealed = 0
                dealed_num += order.dealed
                order.save()
                serializer.save(id=sell_order_instance.id, undealed=sell_order_num, dealed=dealed_num)
                Transaction.objects.create(buy_order_id=order.id, sell_order_id=sell_order_instance.id,
                                           price=order.price, dealed=volume,
                                           stock=int(self.request.data.get('stock')))
                print(
                    "出售订单还未完成 生成的出售订单id为{0} 撮合的购买订单id为{1} 成交数量为{2}".format(sell_order_instance.id, order.id,
                                                                           volume))
            else:
                volume = sell_order_num
                order.undealed -= sell_order_num
                order.dealed += sell_order_num
                dealed_num += volume
                sell_order_num = 0
                order.save()
                serializer.save(id=sell_order_instance.id, undealed=sell_order_num, dealed=dealed_num)
                Transaction.objects.create(buy_order_id=order.id, sell_order_id=sell_order_instance.id,
                                           price=order.price, dealed=volume,
                                           stock=int(self.request.data.get('stock')))
                print(
                    "出售订单还未完成 生成的出售订单id为{0} 撮合的购买订单id为{1} 成交数量为{2}".format(sell_order_instance.id, order.id,
                                                                           volume))
                break

    def create(self, request):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        if request.data.get('type') == 'true':
            sell_order_instance = self.sava_sell_order(request, serializer)
            if isinstance(sell_order_instance, Response):
                return sell_order_instance
            self.exchange_sell_order(request, sell_order_instance, serializer)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
        elif request.data.get('type') == 'false':
            buy_order_instance = self.save_buy_order(request, serializer)
            if isinstance(buy_order_instance, Response):
                return buy_order_instance
            self.exchange_buy_order(request, buy_order_instance, serializer)
            return Response("已成功将订单提交到系统", status=status.HTTP_200_OK)
        else:
            return Response("非法请求", status=status.HTTP_400_BAD_REQUEST)

    """
    List a queryset.
    """

    def list(self, request, *args, **kwargs):
        if self.request.query_params.get('type') == '0':
            # 查看自己的当前委托(正在交易)
            queryset = Order.objects.filter(
                Q(stock=int(self.request.query_params.get('stock'))) & Q(undealed__gt=0) & Q(
                    user_id=self.request.user.id))
        elif self.request.query_params.get('type') == '1':
            # 查看自己的历史委托(产生过交易的)
            queryset = Order.objects.filter(
                Q(stock=int(self.request.query_params.get('stock'))) & Q(dealed__gt=0) & Q(user_id=self.request.user.id))
        else:
            queryset = Order.objects.filter(Q(stock=int(self.request.query_params.get('stock'))) & Q(undealed__gt=0))

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
